<template>
   
    <div class="head" style="margin-bottom: 10px;margin-top: 10px;">
     <el-input type="text" style="height: 30px;width:250px" placeholder="请输入菜品名称" v-model="searchName">
        <template #prefix>
          <el-icon class="el-input__icon"><el-icon><Search /></el-icon></el-icon>
        </template>
     </el-input>
     <el-button type="primary" style="margin-right: 800px;" @click="search">搜索</el-button>
     <!-- 分类搜索 -->
     <el-select v-model="categorySearchName" placeholder="选择分类" 
      style="position: absolute;left: 600px;width: 150px;">
         <el-option v-for="(item,index) in category" :lable="item" :key="index" :value="item.name"
          @click="search">
         </el-option>
      </el-select>
       <!-- 售卖状态搜索 -->
     <el-select v-model="statusSearchName" placeholder="选择状态" 
       style="position: absolute;left: 800px;width: 150px;">
         <el-option @click="statusSearch('在售')">在售</el-option>
         <el-option @click="statusSearch('停售')">停售</el-option>
      </el-select>

     <el-button type="primary" @click="router.push('/adddish')" style="margin-right: 20px;">新增菜品</el-button>
     <!-- <el-button type="primary">新增套餐分类</el-button> -->
    </div>
    
    <el-table :data="tableData" border style="width: 100%;height: 550px;" stripe 
     ref="multipleTableRef"
     @selection-change="handleSelectionChange" >
     <el-table-column type="selection" width="45" align="center"/>
     <el-table-column prop="name" label="菜品名称" width="180" align="center"/>
     <el-table-column prop="img" label="图片" width="180" align="center">
        <template #default="scope">
        <div class="demo-image__preview">
         <el-image
            style="width: 100px; height: 100px"
            :src="dishImgUrl+scope.row.img"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :preview-src-list="imgList"
            :initial-index="4"
            fit="cover"
            />
        </div>
        </template>
     </el-table-column>
     <el-table-column prop="category" label="菜品分类" width="100px" align="center"/>
     <el-table-column prop="price" label="售价"  width="120px" align="center"/>
     <el-table-column prop="status" label="售卖状态"  width="110px" align="center">
      <template #default="scope">
          <el-tag type="default" v-if="scope.row.status=='在售卖'">
             {{ scope.row.status }}
          </el-tag>
          <el-tag type="danger" v-if="scope.row.status=='停售'">
             {{ scope.row.status }}
          </el-tag>
         </template>
     </el-table-column>
     <el-table-column prop="updateTime" label="最后操作时间" width="180px" align="center"/>
     <el-table-column  label="操作">
         <template #default="scope">
          <el-button @click="showInfo(scope.row)" >详情</el-button>
          <el-button @click="updateMsg(scope.row.id)" type="primary">修改</el-button>
          <el-button type="danger" @click="deleteOne(scope.$index,scope.row)">删除</el-button>
          <el-button v-if="scope.row.status=='停售'"  @click="changeStatus(scope.$index,scope.row)">起售</el-button>
          <el-button v-if="scope.row.status=='在售'"  @click="changeStatus(scope.$index,scope.row)">停售</el-button>
         </template>
        
     </el-table-column>
    </el-table>
 
 <!-- 分页组件 -->
 <el-pagination background layout="prev, pager, next,sizes" :total="total" 
:page-sizes="[10, 15, 20, 25]"
  v-model:current-page="currentPage"
  v-model:page-size="pageSize"
  @size-change="handleSizeChange"
  @current-change="handleCurrentChange"/>

     <!-- 删除菜品对话框 -->
     <el-dialog
    v-model="delDialogVisible"
    title="Warning"
    width="30%"
    align-center
  >
    <span>你确定要删除所选菜品吗?</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="delDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="deleteYes">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
 
<!-- 查看详情展示界面 -->
<el-dialog
    v-model="showInfoVisible"
    title="菜品详情"
    width="60%"
    align-center
  >
   
      <span class="dialog-footer">
        <div style="float: left;">
          <div style="font-size: 18px;font-weight: 700;">{{ info.name }}</div>
           <el-image style="width: 150px; height: 150px"
             :src="dishImgUrl+info.img"/>
          <div style="margin-top: 10px;">菜品分类:
            <span style="font-size: 18px;font-weight: 700;">{{ info.category }}</span>
          </div>
          <div  style="margin-top: 10px;">菜品价格:
            <span style="font-size: 18px;font-weight: 700;">{{ info.price }}</span></div>
        </div>
        

          <div style="margin-left: 200px;float: left;">
            <div>口味,标签</div> 
              <li v-for="(item,index) in info.flavourTags" :key="index">
               {{ item.kouwei }}
               {{ item.tags}}
              </li>
          </div>
          <div style="margin-top: 50px;float: left;font-size: 16px;margin-bottom: 20px;">{{ info.description }}</div>
        
      </span>
    
  </el-dialog>
 
 </template>
 
 <script setup lang="ts">
 
 import { ref} from 'vue'
 import { ElTable,ElMessage } from 'element-plus'
 //导入日期工具
 import  {time} from '../utils/time'
 import { onMounted } from 'vue';
 import { useRouter } from 'vue-router';
 import { useStore } from 'vuex';
 //导入api
 import dishApi from '@/api/dish';
 import categoryApi  from '@/api/category';
 //导入图片地址
 import {dishImgUrl} from '@/config/imgconfig'
 
 const router = useRouter()
 const store = useStore()
 
 //查看详情
 const showInfoVisible = ref(false)
 //查看菜品详情
 const showInfo=async (row:any)=>{
   showInfoVisible.value = true
   info.value.name = row.name,
   info.value.price = row.price
   info.value.img = row.img,
   info.value.category = row.category
   info.value.description =row.description
   //获取口味标签列表
   const res = await dishApi.getDishFlavourTags(row.id)
   if(res.code===200){info.value.flavourTags=res.data.flavourTags}
 }
//菜品详情，每点击不同的套餐就会改变
const info = ref({
   name:'',
   price:0,
   category:'',
   flavourTags:[],
   img:'',
   description:''
})


 
 interface Dish {
   name: string
   img: string
   gategory: string
   price: number
   status:string
   time:string
 }
 //多选功能
 const multipleTableRef = ref<InstanceType<typeof ElTable>>()
 const multipleSelection = ref<Dish[]>([])
 const toggleSelection = (rows?: Dish[]) => {
   if (rows) {
     rows.forEach((row) => {
       // TODO: improvement typing when refactor table
       // eslint-disable-next-line @typescript-eslint/ban-ts-comment
       // @ts-expect-error
       multipleTableRef.value!.toggleRowSelection(row, undefined)
     })
   } else {
     multipleTableRef.value!.clearSelection()
   }
 }
 const handleSelectionChange = (val: Dish[]) => {
   multipleSelection.value = val
 }

//页面加载获取数据
onMounted(()=>{
   //获取菜品数据
   getDishes()
   //获取菜品分类数据
   getCategorys()
})

//分页查询菜品数据（无条件)
async function getDishes(){
   //tableData.value = await dishApi.getDishes()
   const data = await dishApi.getDishes(currentPage.value,pageSize.value)
   if(data.code===200){
      tableData.value = data.data.list
      total.value = data.data.total
   }else{
     ElMessage({"message":data.data,"type":"error"})
   }
}
//分类列表
const category = ref([])
//分类搜索名称
const categorySearchName = ref('')
//获取菜品分类数据
async function getCategorys() {
   const res = await categoryApi.getDishCate()
   if(res.code===200){
     category.value=res.data
   }else(ElMessage({"message":res.data,"type":"error"}))
}

//售卖状态搜索名称
const statusSearchName = ref('在售')




//分页查询相关
const currentPage = ref(1)
 const pageSize = ref(10)
 const total = ref(0)

 const handleSizeChange = (val: number) => {
    getDishes()
 }
 const handleCurrentChange = (val: number) => {
    getDishes()
 }



  //搜索菜品名称
 const searchName = ref('')
//聚合搜索
 const search=async ()=>{
  //构建搜索条件对象
   const map ={
      "name":searchName.value,
      "category":categorySearchName.value,
      "status":statusSearchName.value
   }
   var res = await dishApi.pageSearchWrapper(currentPage.value,pageSize.value,map)
    if(res.code == 200){
       tableData.value = res.data.list
       total.value = res.data.total
    }
  }
//根据状态搜索
const statusSearch=(status:any)=>{
    statusSearchName.value = status
    search()
}



 
 
 const tableData = ref([])
   //图片列表
  const imgList = ref([{}])
 

   onMounted(()=>[
      imgList.value = [],
      tableData.value.forEach(item=>imgList.value.push(item.img))
   ])
 

 
 //改变状态
 const changeStatus=async (index:number,row:any)=>{
    var flag = 0;
     if(row.status == '在售'){
        flag = 0;
        //  tableData.value[index].status = '停售'
      }else {
         flag = 1;
      }
   const res = await dishApi.changeStatus(tableData.value[index].id,flag)
   if(res.code===200){
      ElMessage({"message":res.data,"type":"success"})
      getDishes()
   }else{
     ElMessage({"message":res.data,"type":"error"})
   }
     
 }

 //修改菜品,路由传参，跳转
 const updateMsg =(id:any)=>{
  //给store中保存dishid
   store.state.dishId = id;
  router.push({path:`/updatedish/${id}`})
}


/**
 * 删除相关
 */
 const delDialogVisible = ref(false)
 //用来保存待删除的索引数组
 const delIndexs = ref([0])
 //判断是单个删除还是批量删除(开始是单个删除)
 const delOneOrAll = ref(false)
 //删除单个菜品
 const deleteOne=(index:number,row:any)=>{
   delDialogVisible.value = true
   delOneOrAll.value = false
   delIndexs.value[0] = tableData.value[index].id
 }
 //按下确定删除按钮
 const deleteYes=async ()=>{
     var ids: any[] = []
    if(delOneOrAll.value===false){
        ids = delIndexs.value
    }else{
        multipleSelection.value.forEach(item =>{
           ids.push(item.id)
        })
    }

    const data = await dishApi.deleteDishes(ids)
    if(data.code===200){
       delDialogVisible.value = false
       //在执行一遍查询操作
       getDishes()
    }else{
      ElMessage({"message":data.data,"type":"error"})
    }
 }

 //批量删除
 const batchDel=()=>{
   delDialogVisible.value = true
   delOneOrAll.value = true
 }




 const deleteMsg =()=>{ElMessage({message:'删除功能暂未开发', type :'warning'})}
 </script>
 
 
 <style scoped lang="less">
  .head{
     float: right;
  }
 .el-input{
     width: 400px;
     height: 40px;
 }



 .demo-image__error .image-slot {
  font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}
.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}

.el-table__row{
    height: 30px;
}

 </style>